from uuid import UUID, uuid4

from PyQt5.QtWidgets import QVBoxLayout, QWidget, QPushButton, QTreeView, QAbstractItemView
from PyQt5.QtCore import Qt, QModelIndex
from PyQt5.QtGui import QStandardItemModel

from protolib.gui_utils.pyqt5_messageboxes import show_question_messagebox

from data import database

from player.dialogs.editors.album import AlbumEditor

class AlbumList(QWidget):
    ALBUM_NAME, ALBUM_ARTIST, ALBUM_UUID = range(3)

    def __init__(self):
        super().__init__(None)

        layout = QVBoxLayout()

        self.album_list = QTreeView()
        self.album_list.doubleClicked.connect(self.album_list_double_clicked)
        self.album_list.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.album_list_model = QStandardItemModel(0, 3, self)
        self.album_list.setModel(self.album_list_model)
        self.album_list_model.setHeaderData(self.ALBUM_NAME, Qt.Horizontal, "Name")
        self.album_list_model.setHeaderData(self.ALBUM_ARTIST, Qt.Horizontal, "Artist")
        self.album_list_model.setHeaderData(self.ALBUM_UUID, Qt.Horizontal, "UUID")
        layout.addWidget(self.album_list)
        self.refresh_album_list()

        self.create_album_button = QPushButton('Create Album')
        self.create_album_button.clicked.connect(self.create_album)
        layout.addWidget(self.create_album_button)

        self.delete_album_button = QPushButton('Delete Album')
        self.delete_album_button.clicked.connect(self.delete_album)
        layout.addWidget(self.delete_album_button)

        self.setLayout(layout)

    def refresh_album_list(self):
        self.album_list_model.removeRows(0, self.album_list_model.rowCount())
        for uuid in sorted(database['albums'], key=lambda x: str(database['albums'][x]['name']) if database['albums'][x]['name'] else 'No Name', reverse=True):
            self.album_list_model.insertRow(0)
            self.album_list_model.setData(self.album_list_model.index(0, self.ALBUM_NAME), database['albums'][uuid]['name'] if database['albums'][uuid]['name'] else 'No Name')
            self.album_list_model.setData(self.album_list_model.index(0, self.ALBUM_ARTIST), database['artists'][database['albums'][uuid]['artist']]['name'] if database['albums'][uuid]['artist'] else 'Unknown')
            self.album_list_model.setData(self.album_list_model.index(0, self.ALBUM_UUID), str(uuid))

        self.album_list.resizeColumnToContents(self.ALBUM_NAME)
        self.album_list.resizeColumnToContents(self.ALBUM_ARTIST)
        self.album_list.resizeColumnToContents(self.ALBUM_UUID)

    def uuid_from_index(self, index: QModelIndex) -> UUID:
        index = self.album_list_model.index(index.row(), self.ALBUM_UUID)
        item = self.album_list_model.itemFromIndex(index)
        uuid = item.text()
        return UUID(uuid)

    def album_list_double_clicked(self, index: QModelIndex):
        uuid = self.uuid_from_index(index)
        editor = AlbumEditor(uuid)
        editor.exec_()
        self.refresh_album_list()

    def create_album(self):
        uuid = uuid4()
        album = {
            'name': 'New Album',
            'artist': None,
            'cover': None
        }
        database['albums'][uuid] = album
        editor = AlbumEditor(uuid)
        editor.exec_()
        self.refresh_album_list()

    def delete_album(self):
        if not show_question_messagebox('Are you sure?', 'You are about to permanently delete an album. All tracks associated with this album will have there album associations reset. This action cannot be undone.'):
            return
        if not self.album_list.selectedIndexes():
            return
        index = self.album_list.selectedIndexes()[0]
        uuid = self.uuid_from_index(index)
        for track_uuid in database['music']:
            if database['music'][track_uuid]['album'] == uuid:
                database['music'][track_uuid]['album'] = None
        del database['albums'][uuid]
        self.refresh_album_list()
